import React, { Dispatch, SetStateAction } from "react";
import { Button, Checkbox, Form, Input, message, Space } from "antd";
import { useNavigate } from "react-router-dom";
import { loginApi } from "../../api/modules/login";
import { setToken } from "../../store/modules/login/action";
import { setUserinfo } from "../../store/modules/user/action";
import { connect } from "react-redux";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
interface LoginProps {
  setStatus: Dispatch<SetStateAction<boolean>>;
}
const Login: React.FC<LoginProps> = (props: any) => {
    const { setToken, setStatus, setUserinfo } = props;
    const navigate = useNavigate();
    const onFinish = async (values: any) => {
        const result = await loginApi(values);
        if (result.code === 200) {
            message.success("登录成功");
            setUserinfo(result.data);
            setToken(result.data.token);
            navigate({ pathname: "/" });
        } else {
            message.error("账号密码错误！");
        }
    };
    const onFinishFailed = (errorInfo: any) => {
        console.log(errorInfo, "storestorestore");
    };
    // useEffect(() => {
    //   console.log(state);
    // }, [state]);
    return (
        <Form
            name="basic"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
        >
            <Form.Item<FieldType>
                label="用户名"
                name="username"
                rules={[ { required: true, message: "请输入用户名" } ]}
            >
                <Input />
            </Form.Item>

            <Form.Item<FieldType>
                label="密码"
                name="password"
                rules={[ { required: true, message: "请输入密码" } ]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item<FieldType>
                name="记住密码"
                valuePropName="checked"
                wrapperCol={{ offset: 8, span: 16 }}
            >
                <Checkbox>Remember me</Checkbox>
            </Form.Item>
            <Space className="login-btn">
                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                    <Button type="primary" htmlType="submit">
            登录
                    </Button>
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                    <Button onClick={() => setStatus(true)}>注册</Button>
                </Form.Item>
            </Space>
        </Form>
    );
};
const mapStateToProps = (state: any) => state.LoginReducer;
const mapDispatchToProps = { setToken, setUserinfo };
export default connect(mapStateToProps, mapDispatchToProps)(Login);
